﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Remember.WPF.Business
{
    public class LessonDownload
    {
        public void DL()
        {
            WebClient web = new WebClient();
            byte[] buffer = web.DownloadData(new Uri(""));

            WebRequest.Create("");

        }


        /// <summary>
        /// 开始下载
        /// </summary>

        string DownloadUrl = "";
        string FileName = "";
        bool IsDownloading = false;
        long TotalBytes = 0;
        long DownloadBytes = 0;
        public void StartDownload()
        {　　
            //暂停功能只需要将此属性设置为false,则下面的下载循环会跳出
            IsDownloading = true;
            HttpWebRequest request = (HttpWebRequest)FileWebRequest.Create(this.DownloadUrl);
            if (DownloadBytes > 0)
            {
                //此处写入range,实现断点续传
                request.AddRange(DownloadBytes);
            }

            request.BeginGetResponse(ar =>
            {
                var response = request.EndGetResponse(ar);
                if (this.TotalBytes == 0) 
                    this.TotalBytes = response.ContentLength;

                long readBytes = 1024;
                using (var writer = new FileStream(this.FileName, FileMode.OpenOrCreate))
                {
                    using (var stream = response.GetResponseStream())
                    {
                        while (IsDownloading)
                        {
                            byte[] data = new byte[readBytes];
                            int readNumber = stream.Read(data, 0, data.Length);

                            if (readNumber > 0)
                            {
                                writer.Write(data, 0, readNumber);
                                //此处记录已经下载的字节数,也做为进度条功能的实现代码

                                this.DownloadBytes += readNumber;
                            }

                            if (this.DownloadBytes == this.TotalBytes)
                            {　　
                                //通知下载已完成
                                Complete();
                            }
                        }
                    }
                }
            }, null);
        }

        private void Complete()
        {
            throw new NotImplementedException();
        }
    }
}
